package cn.tedu.lianxi1;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;

public class Clint3 {
    public static void main(String[] args) {
        try{
            //1.创建Socket类型的对象，并指定IP地址和端口号
             Socket s = new Socket("127.0.0.1", 8888);
            //Socket s = new Socket("172.88.16.224", 8888);
            //2.使用输入输出流进行通信
            /*
            //提示用户输入要发送的内容
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(System.in));
            System.out.println("请输入要发送的内容：");
            String msg = "张三说：" + br.readLine();
            //让客户端向服务器发送数据"hello"
            PrintStream ps = new PrintStream(s.getOutputStream());
            //ps.println("hello");
            ps.println(msg);
            System.out.println("成功发送数据到服务器！");
            //等待接收服务器的回复，并打印回复的结果
            BufferedReader br2 = new BufferedReader(
                    new InputStreamReader(s.getInputStream()));
            String str2 = br2.readLine();
            System.out.println("服务器发来的消息是：" + str2);
            */
            // BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            PrintStream ps = new PrintStream(s.getOutputStream());
            BufferedReader br2 = new BufferedReader(new InputStreamReader(s.getInputStream()));
            //编程实现客户端不断地和服务器进行通信
            while(true){
                //提示用户输入要发送的内容
                System.out.println("请输入要发送的内容：");
                String msg =new Scanner(System.in).nextLine();
                ps.println(msg);
                //当客户端发送"bye"时，结束循环
                if("bye".equalsIgnoreCase(msg)) break;
                //等待接收服务器的回复，并打印回复的结果
                String str2 = br2.readLine();
                System.out.println("服务器发来的消息是：" + str2);
            }
            //3.关闭Socket对象
            br2.close();
            //br.close();
            ps.close();
            s.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}
